<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;

class MapService
{
    private $host;
    private $key;
    private $cache_prefix = 'map_';

    public function __construct()
    {
        $this->host = 'https://apis.map.qq.com';
        $this->key = config('app.qq_map_key');
    }

    //坐标换地址
    public function geocoder($location)
    {
        $cache_key = $this->cache_prefix . 'geocoder_' . md5($location);
        //缓存1小时
        $result = Cache::remember($cache_key, 3600, function () use ($location) {
            $url = $this->host . '/ws/geocoder/v1/';
            $params = [
                'key' => $this->key,
                'location' => $location
            ];
            $response = Http::get($url, $params);
            $result = $response->json();
            if (isset($result['status']) && $result['status'] == 0) {
                return $result['result'];
            } else {
                throw_invalid_request_exception('map-geocode-fail', $result);
            }
        });
        return $result;
    }

    public function distance($from, $to, $mode = 'driving')
    {
        $cache_key = $this->cache_prefix . 'distance_' . md5($from . $to . $mode);
        //缓存1小时
        $result = Cache::remember($cache_key, 3600, function () use ($from, $to, $mode) {
            $url = $this->host . '/ws/distance/v1/matrix';
            $params = [
                'key' => $this->key,
                'from' => $from,
                'to' => $to,
                'mode' => $mode
            ];
            $response = Http::get($url, $params);
            $result = $response->json();
            if (isset($result['status']) && $result['status'] == 0) {
                return $result['result'];
            } else {
                throw_invalid_request_exception('map-distance-fail', $result);
            }
        });
        return $result;
    }
}
